using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Input;
using IntegratedMeasuring.Utils;
using System;
using System.Threading.Tasks;
using IntegratedMeasuring.ViewModels.Scheme;
using System.Linq;
using Avalonia.Collections;
using IntegratedMeasuring.Storage;
using System.Collections.Generic;
using IntegratedMeasuring.ViewModels.Entity;

namespace IntegratedMeasuring.Pages;

public partial class ModelManagementPage : UserControl
{
    public ModelManagementPage()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private async void OnLoaded(object sender, RoutedEventArgs e)
    {
        var view = new DataGridCollectionView(await BaseDataStorage.Instance.LoadTestConditionsListAsync());
        this.FindControl<DataGrid>("TestConditionsDataGrid").ItemsSource = view;
    }

    private async void ReadInstrumentFileButton_Click(object? sender, RoutedEventArgs e)
    {
        // 使用LoadingHelper执行带加载动画的异步操作
        await LoadingHelper.ExecuteWithLoadingAsync(this, ReadInstrumentFileAsync, "正在读取仪器文件，请稍后...");
    }

    private async void CreateNewFileButton_Click(object? sender, RoutedEventArgs e)
    {
        var dialog = new CreateInstrumentFileDialog();
        var window = this.VisualRoot as Window;
        await dialog.ShowDialog(window);
    }

    private async Task ReadInstrumentFileAsync()
    {
        TestConditions? testConditions = await InstrumentControlHelper.LoadTestConditionFromMachine();

        if (testConditions != null)
        {
            // 显示成功通知
            NotificationHelper.ShowSuccess("读取完成", "仪器文件读取成功，请确认后进行保存");

            var dialog = new TestConditionPreviewDialog(testConditions);
            var window = this.VisualRoot as Window;
            var result = await dialog.ShowDialog<dynamic>(window);
            if (result != null && result.result == true)
            {
                testConditions.Name = result.name;
                testConditions.ApplicableInstrument = (int)GV.InstrumentModel;
                if (await BaseDataStorage.Instance.SaveTestConditionsAsync(testConditions))
                {
                    NotificationHelper.ShowSuccess("操作提示", "机种文件保存成功");
                    var view = new DataGridCollectionView(await BaseDataStorage.Instance.LoadTestConditionsListAsync());
                    this.FindControl<DataGrid>("TestConditionsDataGrid").ItemsSource = view;
                    MesHandler.UploadSingleTestConfigToMes(testConditions);
                }
            }
            else
            {
                NotificationHelper.ShowInfo("操作提示", "用户取消保存");
            }
        }
        else
        {
            // 显示错误通知
            NotificationHelper.ShowError("读取失败", "无法读取仪器文件");
        }
    }

    private async void SaveAsSelectedButton_Click(object? sender, RoutedEventArgs e)
    {
        var dataGrid = this.FindControl<DataGrid>("TestConditionsDataGrid");
        var collectionView = dataGrid.ItemsSource as DataGridCollectionView;
        if (collectionView == null) 
        {
            NotificationHelper.ShowError("错误", "无法获取DataGrid数据");
            return;
        }
        
        var selected = collectionView.Cast<TestConditions>().Where(x => x.IsSelected == true).ToList();
        
        if (selected.Count == 0)
        {
            NotificationHelper.ShowWarning("操作提示", "请在下方表格选中要操作的项目");
            return;
        }
        if (selected.Count > 1)
        {
            NotificationHelper.ShowWarning("操作提示", "另存为不能同时对多条进行操作");
            return;
        }
        var origin = selected.First();
        var dialog = new SaveAsDialog(origin.Name, origin.Remarks);
        var window = this.VisualRoot as Window;
        var result = await dialog.ShowDialog<bool?>(window);
        if (result == true)
        {
            var newItem = new TestConditions
            {
                Name = dialog.InputName ?? string.Empty,
                Remarks = dialog.InputRemarks ?? string.Empty,
                SourceData = origin.SourceData,
                BeautifyData = origin.BeautifyData,
                CreateTime = DateTime.Now,
                ApplicableInstrument = (int)GV.InstrumentModel
            };
            if (await BaseDataStorage.Instance.SaveTestConditionsAsync(newItem))
            {
                NotificationHelper.ShowSuccess("操作提示", "机种文件另存为成功");
                var view = new DataGridCollectionView(await BaseDataStorage.Instance.LoadTestConditionsListAsync());
                dataGrid.ItemsSource = view;
            }
        }
    }

    private async void DeleteSelectedButton_Click(object? sender, RoutedEventArgs e)
    {
        var dataGrid = this.FindControl<DataGrid>("TestConditionsDataGrid");
        var collectionView = dataGrid.ItemsSource as DataGridCollectionView;
        if (collectionView == null) return;
        
        var selected = collectionView.Cast<TestConditions>().Where(x => x.IsSelected == true).ToList();
        if (selected.Count == 0)
        {
            NotificationHelper.ShowWarning("操作提示", "请在下方表格选中要操作的项目");
            return;
        }
        
        // 显示确认弹窗
        var confirmDialog = new ConfirmDialog("确认要删除选中的机种吗？删除后不可恢复！");
        var window = this.VisualRoot as Window;
        var result = await confirmDialog.ShowDialog<bool?>(window);
        
        if (result == true)
        {
            foreach (var item in selected)
            {
                await BaseDataStorage.Instance.DeleteTestConditionsAsync(item.Id);
            }
            NotificationHelper.ShowSuccess("操作提示", "删除成功");
            var view = new DataGridCollectionView(await BaseDataStorage.Instance.LoadTestConditionsListAsync());
            dataGrid.ItemsSource = view;
        }
    }

    private async void TestConditionsDataGrid_DoubleTapped(object? sender, TappedEventArgs e)
    {
        try
        {
            var dataGrid = this.FindControl<DataGrid>("TestConditionsDataGrid");
            if (dataGrid.SelectedItem is TestConditions selectedItem)
            {
                // 使用LoadingHelper执行带加载动画的异步操作
                await LoadingHelper.ExecuteWithLoadingAsync(this, async () =>
                {
                    // 从数据库加载完整的TestConditions（包含SourceData和解析后的BeautifyData）
                    var testConditions = await BaseDataStorage.Instance.QueryTestConditionsByIdAsync(selectedItem.Id);
                    if (testConditions != null)
                    {
                        var detailDialog = new TestConditionDetailDialog(testConditions);
                        var window = this.VisualRoot as Window;
                        await detailDialog.ShowDialog(window);
                    }
                    else
                    {
                        NotificationHelper.ShowError("错误", "无法加载机种详情");
                    }
                }, "正在加载机种详情，请稍后...");
            }
        }
        catch (Exception ex)
        {
            NotificationHelper.ShowError("显示详情失败", ex.Message);
        }
    }
}